package com.hd.trans.files.domain;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import com.hd.trans.files.bean.Video;
import com.hd.trans.files.model.FileSortModel;
import com.hd.trans.files.repository.VideoDataRepository;
import com.hd.trans.utils.SharedFileUtils;

import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;

/**
 * Author: yangtianwen
 * Time: 2021/12/14
 * Des: 视频数据源业务类
 */
public class RequestVideoDataUserCase extends BaseUseCase {

    private final VideoDataRepository mVideoDataRepository;

    private Disposable mLoadVideoDisposable;

    private MutableLiveData<List<Video>> mVideoDataObserver;
    private MutableLiveData<String> mCurrentPathObserver;

    public RequestVideoDataUserCase() {
        mVideoDataRepository = new VideoDataRepository();
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        release();
    }

    public void loadVideosDataWithDir(String path, FileSortModel.ModeItem sortModeItem, Callback<List<Video>> callback) {
        mCurrentPathObserver.setValue(path);
        mLoadVideoDisposable = mVideoDataRepository.requestVideosWithDir(path, sortModeItem)
                .subscribe(videos -> {
                    if (callback != null) callback.onValueChange(videos);
                    if (mVideoDataObserver != null) {
                        mVideoDataObserver.setValue(videos);
                    }
                });
    }


    /**
     * 加载媒体库的视频数据
     */
    public void loadVideoData(Context context, Callback<List<Video>> callback) {
        FileSortModel.ModeItem sortModeItem = SharedFileUtils.getInstance(context).getFileSortModeItem();
        mLoadVideoDisposable = mVideoDataRepository.requestVideos(context.getContentResolver(), sortModeItem)
                .subscribe(videos -> {
                    if (mVideoDataObserver != null) {
                        mVideoDataObserver.setValue(videos);
                    }
                    if (callback != null) callback.onValueChange(videos);
                });
    }

    public RequestVideoDataUserCase addVideoDataObserver(MutableLiveData<List<Video>> videoDataObserver) {
        this.mVideoDataObserver = videoDataObserver;
        return this;
    }

    public RequestVideoDataUserCase addCurrentPathObserver(MutableLiveData<String> currentPathObserver) {
        this.mCurrentPathObserver = currentPathObserver;
        return this;
    }

    public RequestVideoDataUserCase addLifecycleOwner(LifecycleOwner owner) {
        owner.getLifecycle().addObserver(this);
        return this;
    }

    public void release() {
        if (mLoadVideoDisposable != null) {
            mLoadVideoDisposable.dispose();
        }
    }
}
